import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {RootState} from '../../store';
import {Avatar, Button, Card, message, Popover, QRCode, Empty, Spin} from 'antd';
import {DownloadOutlined, EditOutlined, LinkOutlined, LockOutlined, ShareAltOutlined, HeartOutlined} from '@ant-design/icons';
import Header from '../../components/Header/Header';
import {useParams, useNavigate} from 'react-router-dom';
import {setLoginUser} from "@/store/loginUser.tsx";
import {getUserInfo} from '../../api/userController.ts';
import {getUserLikedPosts} from '../../api/communityPostLikeController';
import CommunityPost from '../../components/CommunityPost';

export const UserInfo: React.FC = () => {
    let loginUser: API.UserVo = useSelector((state: RootState) => state.loginUser);
    const {id} = useParams();
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const [likedPosts, setLikedPosts] = useState<API.CommunityPostVO[]>([]);
    const [loading, setLoading] = useState(false);

    //获取用户信息
    const getUserInfos = async () => {
        const res = await getUserInfo({
            id: id
        });
        if (res.code === 200) {
            dispatch(setLoginUser(res.data));
        }
    }

    // 获取用户点赞的帖子
    const getLikedPosts = async () => {
        setLoading(true);
        try {
            const res = await getUserLikedPosts({
                current: 1,
                pageSize: 10
            });
            if (res.code === 200 && res.data) {
                setLikedPosts(res.data.records || []);
            }
        } catch (error) {
            console.error('Failed to fetch liked posts:', error);
            message.error('获取点赞帖子失败');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (loginUser.id != Number(id)) {
            //根据id获取用户信息
            getUserInfos();
        }
        // 无论是否是当前登录用户，都获取点赞列表
        getLikedPosts();
    }, [id]);

    const currentURL = window.location.href;

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
    };


    const handleDownloadQR = () => {
        const canvas = document.querySelector('.ant-qrcode canvas') as HTMLCanvasElement;
        if (canvas) {
            const url = canvas.toDataURL();
            const a = document.createElement('a');
            a.download = 'qrcode.png';
            a.href = url;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        }
    };

    const handleCopyLink = () => {
        navigator.clipboard.writeText(currentURL).then(() => {
            message.success('链接已复制到剪贴板');
        });
    };

    const qrCodeContent = (
        <div className="w-[160px]">
            <div className="p-0 flex flex-col items-center">
                <QRCode value={currentURL} size={140}/>
                <div className="mt-2 flex gap-2">
                    <Button
                        size="small"
                        icon={<DownloadOutlined/>}
                        onClick={handleDownloadQR}
                    >
                        下载
                    </Button>
                    <Button
                        size="small"
                        icon={<LinkOutlined/>}
                        onClick={handleCopyLink}
                    >
                        复制
                    </Button>
                </div>
            </div>
        </div>
    );

    return (
        <>
            {/* 表头 */}
            <Header></Header>
            {/* 内容 */}
            <div className="container mx-auto px-4 py-8 min-[700px]:px-4 max-[699px]:p-0">
                <Card
                    className="max-w-[1180px] w-full mx-auto min-[900px] relative max-[799px]:border-none"
                    bodyStyle={{padding: window.innerWidth < 700 ? '12px' : '24px'}}
                >
                    {/* 分享按钮 - 在小于xl屏幕尺寸时隐藏 */}
                    <div className="absolute top-4 right-4 hidden xl:block">
                        <Popover
                            content={qrCodeContent}
                            trigger="hover"
                            placement="bottomRight"
                            overlayClassName="transition-opacity duration-300"
                        >
                            <Button
                                type="text"
                                icon={<ShareAltOutlined/>}
                                className="text-xl hover:text-blue-500 transition-colors"
                            />
                        </Popover>
                    </div>

                    <div className="flex flex-col md:flex-row">
                        {/* 左侧头像部分 */}
                        <div className="md:w-48 flex flex-col items-center">
                            <Avatar
                                size={120}
                                src={loginUser.avatarUrl}
                                className="border-4 border-gray-200"
                            />
                        </div>

                        {/* 右侧信息部分 */}
                        <div className="flex-1 md:ml-10 mt-4 md:mt-0">
                            {/* 用户名和昵称部分 */}
                            <div className="mb-6">
                                <h1 className="text-2xl font-bold ">
                                    {loginUser.nickName}
                                </h1>
                                <p className="mt-1 ">
                                    {loginUser.username == "" ? "未设置" : "@" + loginUser.username}
                                </p>
                            </div>

                            {/* 用户详细信息 */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <InfoItem label="邮箱" value={loginUser.email || '未设置'}/>
                                <InfoItem label="手机号码" value={loginUser.phone || '未设置'}/>
                                <InfoItem label="性别" value={loginUser.gender === 0 ? '男' : '女'}/>
                                <InfoItem label="地址" value={loginUser.address || '未设置'}/>
                                <InfoItem label="用户角色" value={loginUser.userRole === 'user' ? '普通用户' : '管理员'}/>
                                <InfoItem label="微信" value={loginUser.wxcode || '未绑定'}/>
                                <InfoItem label="注册时间" value={formatDate(loginUser.createTime || '')}/>
                                <InfoItem label="最后更新" value={formatDate(loginUser.updateTime || '')}/>
                            </div>

                            {/* 底部按钮 */}
                            <div className="flex justify-end mt-8 space-x-4">
                                <Button
                                    icon={<EditOutlined/>}
                                    onClick={() => navigate(`/user/edit/${id}`)}
                                >
                                    <p style={{color: '#fff !important'}}>编辑资料</p>
                                </Button>
                                <Button
                                    icon={<LockOutlined/>}
                                >
                                    修改密码
                                </Button>
                            </div>
                        </div>
                    </div>
                </Card>

                {/* 点赞帖子列表卡片 */}
                <Card 
                    className="max-w-[1180px] w-full mx-auto mt-8"
                    title={
                        <div className="flex items-center">
                            <HeartOutlined className="mr-2 text-red-500" />
                            <span>我的点赞</span>
                        </div>
                    }
                >
                    {loading ? (
                        <div className="flex justify-center py-8">
                            <Spin size="large" />
                        </div>
                    ) : likedPosts.length > 0 ? (
                        <div className="space-y-4">
                            {likedPosts.map((post) => (
                                <CommunityPost
                                    key={post.id}
                                    post={post}
                                    sectionId={post.categorycode}
                                    onRefreshList={getLikedPosts}
                                />
                            ))}
                        </div>
                    ) : (
                        <Empty
                            description="暂无点赞的帖子"
                            className="py-8"
                        />
                    )}
                </Card>
            </div>
        </>
    );
};

interface InfoItemProps {
    label: string,
    value: string
}

const InfoItem: React.FC<InfoItemProps> = ({label, value}) => (
    <div className="py-2">
        <span className="dark:text-gray-300 font-semibold">{label}：</span>
        <span className="dark:text-gray-200 ml-2">{value}</span>
    </div>
);

export default UserInfo;
